package com.hardware.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hardware.common.R;
import com.hardware.controller.front.ShopTypeController;
import com.hardware.dto.ShopDto;
import com.hardware.entity.*;
import com.hardware.service.*;
import com.hardware.service.category.ShopCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 分类管理
 */
@RestController
@RequestMapping("/shop")
@Slf4j
public class ShopController {
    @Autowired
    private ShopService shopService;
    @Autowired
    private ShopTypeService shopTypeService;
    @Autowired
    private ShopCategoryService categoryService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private OrderDetailService orderDetailService;
    /**
     * 后台分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name, String type){

        //构造分页构造器对象
        Page<Shop> pageInfo = new Page<>(page,pageSize);
        Page<ShopDto> shopDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Shop> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(name != null,Shop::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Shop::getUpdateTime);
        //库存查询条件
        if(type != null && type.equals("stock")){
            queryWrapper.le(Shop::getStock,50);
        }
        //执行分页查询
        shopService.page(pageInfo,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,shopDtoPage,"records");

        List<Shop> records = pageInfo.getRecords();

        List<ShopDto> list = records.stream().map((item) -> {
            ShopDto shopDto = new ShopDto();
            BeanUtils.copyProperties(item,shopDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            ShopCategory category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                shopDto.setCategoryName(categoryName);
            }

            Long supplierId = item.getSupplierId(); //供应人id
            Supplier supplier = supplierService.getById(supplierId);
            if(supplier != null){
                shopDto.setSupplierCompany(supplier.getCompany());
                shopDto.setSupplierName(supplier.getName());
            }


            return shopDto;
        }).collect(Collectors.toList());

        shopDtoPage.setRecords(list);

        return R.success(shopDtoPage);
    }

    /**
     * 后台新增商品
     * @param shopDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "cache:shop", allEntries = true)
    public R<String> save(@RequestBody ShopDto shopDto){
        shopService.saveWithType(shopDto);
        return R.success("新增商品成功");
    }

    /**
     * 根据id查询商品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @Cacheable(value = "cache:shop:id",key = "#id", unless = "#result == null")
    public R<ShopDto> get(@PathVariable Long id){

        ShopDto shopDto = shopService.getByIdWithType(id);

        return R.success(shopDto);
    }

    /**
     * 修改商品
     * @param shopDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "cache:shop", allEntries = true)
    public R<String> update(@RequestBody ShopDto shopDto){

        shopService.updateWithType(shopDto);

        return R.success("修改商品成功");
    }

    /**
     * 后台根据商品id 修改 启售与停售
     * @param status 1 启售,0停售
     * @param ids  商品id
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "cache:shop", allEntries = true)
    public R<String> updateByid(@PathVariable Integer status, @RequestParam List<Long> ids) {
        //条件构造器
        LambdaQueryWrapper<Shop> lqw = new LambdaQueryWrapper<>();
        lqw.in(Shop::getId,ids);
        List<Shop> collect = ids.stream().map((item) -> {
            Shop shop = new Shop();
            shop.setStatus(status);
            shop.setId(item);
            return shop;
        }).collect(Collectors.toList());
        shopService.updateBatchById(collect);
        return R.success("更新成功");
    }

    /**
     * 后台删除商品
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "cache:shop", allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids){
        shopService.removeWithShop(ids);
        return R.success("商品数据删除成功");
    }

    /**
     * 前台，商品列表
     * @param shop
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "cache:shop",key = "#shop.categoryId +'_'+ #shop.status", unless = "#result == null")
    public R<List<ShopDto>> list(Shop shop){
        //1.条件构造
        LambdaQueryWrapper<Shop> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(shop.getCategoryId() != null, Shop::getCategoryId,shop.getCategoryId());
        lqw1.eq(shop.getStatus() != null, Shop::getStatus,shop.getStatus());
        List<Shop> list = shopService.list(lqw1);

        //2.
        List<ShopDto> shopDtos = list.stream().map((item) -> {
            ShopDto shopDto = new ShopDto();
            //复制基本信息
            BeanUtils.copyProperties(item, shopDto);
            //获取月销售数量
            shopDto.setSaleNum(
                    getSaleNum(item.getId())
            );
            //获取分类名称
            ShopCategory category = categoryService.getById(item.getCategoryId());
            if (category != null) shopDto.setCategoryName(category.getName());

            return shopDto;
        }).collect(Collectors.toList());
        return R.success(shopDtos);
    }

    /**
     * 商品类型
     * @param id
     * @return
     */
    @GetMapping("/type/{id}")
    @Cacheable(value = "cache:shopType", key = "#id", unless = "#result == null")
    public R<List<ShopType>> shopDetails(@PathVariable Long id){

        LambdaQueryWrapper<ShopType> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(ShopType::getShopId,id);
        lqw1.orderByAsc(ShopType::getTypePrice);
        List<ShopType> list = shopTypeService.list(lqw1);

        return R.success(list);
    }

    /**
     * 销售管理
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/salePage")
    public R<Page> salePage(int page,int pageSize,String name){
        Page<Shop> pageInfo = new Page<>(page,pageSize);
        Page<Sale> salePage = new Page<>();

        LambdaQueryWrapper<Shop> lqw = new LambdaQueryWrapper<>();
        lqw.eq(name != null,Shop::getName,name);
        shopService.page(pageInfo,lqw);
        BeanUtils.copyProperties(pageInfo,salePage,"records");
        List<Shop> records = pageInfo.getRecords();
        List<Sale> sales = records.stream().map((item) -> {
            Sale sale = new Sale();
            BeanUtil.copyProperties(item, sale);
            //获取月销售数量
            sale.setVolume(
                    getSaleNum(item.getId())
            );

            return sale;
        }).collect(Collectors.toList());
        salePage.setRecords(sales);
        return R.success(salePage);

    }

    /**
     * 根据id 查询该商品的销量
     * @param id
     * @return
     */
    public Integer getSaleNum(Long id){
        //获取月销售数量
        LambdaQueryWrapper<OrderDetail> lqw3 = new LambdaQueryWrapper<>();
        lqw3.eq(OrderDetail::getShopId, id);
        int saleNum = orderDetailService.count(lqw3);
        return saleNum;
    }

}
